package estring

import (
	"fmt"
	"math"
	"regexp"
	"strconv"
	"strings"
	"time"
)

/*
func FormatTimeHeader(when time.Time) []byte {
	y, mo, d := when.Date()
	h, mi, s := when.Clock()
	//len("2006/01/02 15:04:05 ")==20
	var buf [20]byte

	buf[0] = y1[y/1000%10]
	buf[1] = y2[y/100]
	buf[2] = y3[y-y/100*100]
	buf[3] = y4[y-y/100*100]
	buf[4] = '/'
	buf[5] = mo1[mo-1]
	buf[6] = mo2[mo-1]
	buf[7] = '/'
	buf[8] = d1[d-1]
	buf[9] = d2[d-1]
	buf[10] = ' '
	buf[11] = h1[h]
	buf[12] = h2[h]
	buf[13] = ':'
	buf[14] = mi1[mi]
	buf[15] = mi2[mi]
	buf[16] = ':'
	buf[17] = s1[s]
	buf[18] = s2[s]
	buf[19] = ' '
	return buf[0:]
}
*/
func TimeFormat(t int64) string {
	return time.Unix(t, 0).Format("2006-01-02 15:04:05")
}

func Time(value string) (t time.Time, err error) {
	t, err = time.Parse("2006-01-02 15:04:05", value)
	return
}

//格式化浮点数
func FormatFloat(f float64) (s string) {
	s = fmt.Sprintf("%.6f", f)
	if strings.Contains(s, ".") {
		s = strings.TrimRight(s, "0")
	}
	if strings.HasSuffix(s, ".") {
		s = strings.TrimSuffix(s, ".")
	}
	return
}

//获取key在行中的索引号
func GetIndex(line string, key string) int {
	ss := strings.Split(line, ",")
	for i, s := range ss {
		s = strings.TrimSpace(s)
		if s == key {
			return i
		}
	}
	return -1
}

//去掉为0之后的字符
func String(data []byte) string {
	l := len(data)
	for i := 0; i < l; i++ {
		if data[i] == 0 {
			return string(data[:i])
		}
	}
	return string(data)
}

/** 带数字的字符串比较
 *"abc100" > "abc9" true
 */
func CompareWithNumber(s1 string, s2 string) bool {
	reg := regexp.MustCompile("([A-Za-z]*)([\\d]*)")
	ss1 := reg.FindStringSubmatch(s1)
	ss2 := reg.FindStringSubmatch(s2)
	if len(ss1) == len(ss2) && len(ss1) == 3 {
		if ss1[1] < ss2[1] {
			return true
		} else if ss1[1] > ss2[1] {
			return false
		} else {
			i1, e1 := strconv.Atoi(ss1[2])
			i2, e2 := strconv.Atoi(ss2[2])
			if e1 != nil && e2 != nil {
				return ss1[2] < ss2[2]
			}
			return i1 < i2
		}
	}
	return s1 < s2
}

//是否是回车换行
func IsCrLf(r rune) bool {
	if r == '\r' || r == '\n' {
		return true
	}
	return false
}

//字符串是否在一个数组中
func StringInArray(str string, stringArray []string) bool {
	str = strings.ToUpper(str)
	for _, s := range stringArray {
		if str == s {
			return true
		}
	}
	return false
}

//不区分大小写的字符串比较
func CompareNoCase(s1, s2 string) bool {
	return strings.ToLower(s1) == strings.ToLower(s2)
}

//路径比较
func ComparePath(s1, s2 string) bool {
	s1 = strings.Replace(s1, "\\", "/", -1)
	s2 = strings.Replace(s2, "\\", "/", -1)
	return strings.ToLower(s1) == strings.ToLower(s2)
}

//查找字符串
func FindString(line, key string) string {
	ss := strings.Split(line, ";")
	for _, s := range ss {
		ss := strings.SplitN(s, "=", 2)
		if len(ss) == 2 {
			if strings.TrimSpace(ss[0]) == key {
				return strings.TrimSpace(ss[1])
			}
		}
	}
	return ""
}

func FloatEqual(a, b float64) bool {
	return math.Abs(a-b) < 0.00001
}
